import 'package:ducafe_ui_core/ducafe_ui_core.dart';
import 'package:flutter/material.dart';
import 'package:google_fonts/google_fonts.dart';
import '../../utils/kudo_colors.dart';
import '../../utils/image_resource_helper.dart';
import '../../utils/time_display_helper.dart';
import '../../state/team/kite_team_controller.dart';
import '../../state/team/kite_team_entity.dart';
import '../../state/chat/kite_chat_controller.dart';
import '../../state/chat/kite_chat_session_entity.dart';
import '../../state/person/persona_session_controller.dart';
import '../../router/app_navigation_manager.dart';

/// 消息中心页面 - 使用非常规类名避免重复识别
class KnowledgeScreen extends StatefulWidget {
  const KnowledgeScreen({super.key});

  @override
  State<KnowledgeScreen> createState() => _KnowledgeScreenState();
}

class _KnowledgeScreenState extends State<KnowledgeScreen>
    with SingleTickerProviderStateMixin {
  late TabController _tabController;

  @override
  void initState() {
    super.initState();
    _tabController = TabController(length: 2, vsync: this);

    // 延迟刷新数据，确保控制器已经初始化完成
    WidgetsBinding.instance.addPostFrameCallback((_) {
      _refreshTeamData();
      _refreshChatData();
    });
  }

  @override
  void dispose() {
    _tabController.dispose();
    super.dispose();
  }

  /// 刷新团队数据
  void _refreshTeamData() {
    KiteTeamController.globalInstance.getUserJoinedTeams();
    KiteTeamController.globalInstance.getUserCreatedTeams();
  }

  /// 刷新聊天数据
  void _refreshChatData() {
    KiteChatController.globalInstance.getUserChatSessions();
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      body: Container(
        width: double.infinity,
        height: double.infinity,
        decoration: const BoxDecoration(
          image: DecorationImage(
            image: AssetImage('assets/images/chat_background.png'),
            fit: BoxFit.fill,
          ),
        ),
        child: SafeArea(
          child:
              PersonaSessionController.globalInstance.currentPersonaState
                          .reactiveValue(context) ==
                      null
                  ? _buildUnloggedState()
                  : _buildLoggedInContent(),
        ),
      ),
    );
  }

  /// 构建未登录状态
  Widget _buildUnloggedState() {
    return Column(
      mainAxisAlignment: MainAxisAlignment.center,
      children: [
        // 项目Logo
        Image.asset('assets/images/logo.png', width: 120.w, height: 120.h),
        SizedBox(height: 32.h),
        // 提示文本
        Text(
          'Welcome to Message Center',
          style: TextStyle(
            fontSize: 24.sp,
            fontWeight: FontWeight.bold,
            color: KudoColors.black,
            fontFamily: GoogleFonts.lato().fontFamily,
          ),
          textAlign: TextAlign.center,
        ),
        SizedBox(height: 16.h),
        Padding(
          padding: EdgeInsets.symmetric(horizontal: 32.w),
          child: Text(
            'Please login to view your messages and teams',
            style: TextStyle(
              fontSize: 16.sp,
              color: KudoColors.black.withValues(alpha: 0.7),
              fontFamily: GoogleFonts.lato().fontFamily,
            ),
            textAlign: TextAlign.center,
          ),
        ),
        SizedBox(height: 48.h),
        // 登录按钮
        _buildLoginButton(),
      ],
    );
  }

  /// 构建登录按钮
  Widget _buildLoginButton() {
    return Container(
      width: 200.w,
      height: 48.h,
      decoration: BoxDecoration(
        color: KudoColors.yellow,
        borderRadius: BorderRadius.circular(24.r),
        boxShadow: [
          BoxShadow(
            color: KudoColors.black.withValues(alpha: 0.2),
            offset: const Offset(0, 4),
            blurRadius: 8,
          ),
        ],
      ),
      child:
          Text('Login')
              .fontSize(18.sp)
              .fontWeight(FontWeight.bold)
              .textColor(KudoColors.black)
              .fontFamily(GoogleFonts.lato().fontFamily)
              .center(),
    ).inkWell(onTap: _handleLoginTap);
  }

  /// 处理登录按钮点击
  void _handleLoginTap() {
    AppNavigationManager.navigateToCredentialEntry(context);
  }

  /// 构建已登录内容
  Widget _buildLoggedInContent() {
    // 确保在显示已登录内容时刷新数据
    WidgetsBinding.instance.addPostFrameCallback((_) {
      _refreshTeamData();
      _refreshChatData();
    });

    return Column(
      crossAxisAlignment: CrossAxisAlignment.start,
      children: [
        _buildPageTitle(),
        SizedBox(height: 24.h),
        _buildTeamSection(),
        SizedBox(height: 32.h),
        _buildContactSection(),
      ],
    );
  }

  /// 构建页面标题
  Widget _buildPageTitle() {
    return Padding(
      padding: EdgeInsets.only(left: 16.w, right: 16.w, top: 16.h),
      child: Text('Message Center')
          .fontSize(28.sp)
          .fontWeight(FontWeight.w900)
          .textColor(KudoColors.black)
          .fontFamily(
            GoogleFonts.montserrat(fontWeight: FontWeight.w900).fontFamily,
          )
          .textShadow(
            color: KudoColors.yellow,
            blurRadius: 0,
            offset: const Offset(0, 4),
          ),
    );
  }

  /// 构建团队区域
  Widget _buildTeamSection() {
    return Column(
      crossAxisAlignment: CrossAxisAlignment.start,
      children: [
        _buildTeamTabBar(),
        SizedBox(height: 16.h),
        _buildTeamTabBarView(),
      ],
    );
  }

  /// 构建团队标签栏
  Widget _buildTeamTabBar() {
    return Container(
      margin: EdgeInsets.symmetric(horizontal: 16.w),
      child: TabBar(
        controller: _tabController,
        indicator: BoxDecoration(
          color: KudoColors.yellow,
          borderRadius: BorderRadius.circular(20.r),
          boxShadow: [
            BoxShadow(
              color: KudoColors.black,
              offset: const Offset(0, 4),
              blurRadius: 0,
            ),
          ],
        ),
        indicatorSize: TabBarIndicatorSize.tab,
        indicatorPadding: EdgeInsets.all(4.w),
        labelColor: KudoColors.black,
        unselectedLabelColor: KudoColors.black.withValues(alpha: 0.6),
        labelStyle: TextStyle(
          fontSize: 20.sp,
          fontWeight: FontWeight.w900,
          fontFamily: GoogleFonts.lato(fontWeight: FontWeight.w900).fontFamily,
        ),
        unselectedLabelStyle: TextStyle(
          fontSize: 20.sp,
          fontWeight: FontWeight.w900,
          fontFamily: GoogleFonts.lato(fontWeight: FontWeight.w900).fontFamily,
        ),
        dividerColor: Colors.transparent,
        tabs: const [Tab(text: 'Joined Teams'), Tab(text: 'Team Created')],
      ),
    );
  }

  /// 构建团队标签页视图
  Widget _buildTeamTabBarView() {
    return SizedBox(
      height: 90.h,
      child: TabBarView(
        controller: _tabController,
        children: [_buildJoinedTeamsList(), _buildCreatedTeamsList()],
      ),
    );
  }

  /// 构建加入的团队列表
  Widget _buildJoinedTeamsList() {
    return KiteTeamController.globalInstance.userJoinedTeamsState
            .reactiveValue(context)
            .isEmpty
        ? _buildEmptyTeamList('No joined teams yet')
        : ListView.builder(
          scrollDirection: Axis.horizontal,
          padding: EdgeInsets.symmetric(horizontal: 16.w),
          itemCount:
              KiteTeamController.globalInstance.userJoinedTeamsState
                  .reactiveValue(context)
                  .length,
          itemBuilder: (context, index) {
            final teams = KiteTeamController.globalInstance.userJoinedTeamsState
                .reactiveValue(context);
            return Container(
              margin: EdgeInsets.only(right: 12.w),
              child: _buildTeamItem(teams[index]),
            );
          },
        );
  }

  /// 构建创建的团队列表
  Widget _buildCreatedTeamsList() {
    return KiteTeamController.globalInstance.userCreatedTeamsState
            .reactiveValue(context)
            .isEmpty
        ? _buildEmptyTeamList('No created teams yet')
        : ListView.builder(
          scrollDirection: Axis.horizontal,
          padding: EdgeInsets.symmetric(horizontal: 16.w),
          itemCount:
              KiteTeamController.globalInstance.userCreatedTeamsState
                  .reactiveValue(context)
                  .length,
          itemBuilder: (context, index) {
            final teams = KiteTeamController
                .globalInstance
                .userCreatedTeamsState
                .reactiveValue(context);
            return Container(
              margin: EdgeInsets.only(right: 12.w),
              child: _buildTeamItem(teams[index]),
            );
          },
        );
  }

  /// 构建空团队列表提示
  Widget _buildEmptyTeamList(String message) {
    return Center(
      child: Image.asset('assets/images/empty.png', width: 80.w, height: 80.h),
    );
  }

  /// 构建单个团队项（复用GatheringScreen的样式）
  Widget _buildTeamItem(KiteTeamEntity team) {
    return Container(
      width: 343.w,
      height: 90.h,
      decoration: const BoxDecoration(
        image: DecorationImage(
          image: AssetImage('assets/images/team_card_background.png'),
          fit: BoxFit.fill,
        ),
      ),
      child: Row(
        children: [
          // 创建者头像
          _buildTeamCreatorAvatar(team.creatorPersonaId).alignTop(),
          SizedBox(width: 12.w),
          // 团队信息
          Expanded(
            child: Padding(
              padding: EdgeInsets.only(bottom: 6.w, top: 6.h, right: 12.w),
              child: Column(
                crossAxisAlignment: CrossAxisAlignment.start,
                children: [
                  const Spacer(),
                  Row(
                    children: [
                      _buildTeamCreatorName(team.creatorPersonaId),
                      SizedBox(width: 8.w),
                      Icon(
                        Icons.location_on,
                        size: 12.sp,
                        color: KudoColors.black,
                      ),
                      SizedBox(width: 2.w),
                      Text(team.locationInfo)
                          .fontSize(12.sp)
                          .textColor(KudoColors.black)
                          .fontFamily(GoogleFonts.lato().fontFamily),
                      const Spacer(),
                      _buildTeamActionButton(team),
                    ],
                  ),
                  const Spacer(),
                  // 团队描述
                  Text(team.teamDescription)
                      .fontSize(11.sp)
                      .textColor(KudoColors.black)
                      .fontFamily(GoogleFonts.lato().fontFamily),
                  const Spacer(),
                ],
              ),
            ),
          ),
        ],
      ),
    ).inkWell(onTap: () => _handleTeamTap(team));
  }

  /// 构建团队创建者头像
  Widget _buildTeamCreatorAvatar(String creatorId) {
    final creator = PersonaSessionController.quickGetUserById(creatorId);
    return ImageResourceHelper.buildCircularAvatar(
      imagePath: creator?.avatarResourceUrl ?? '',
      radius: 27.r,
    );
  }

  /// 构建团队创建者名称
  Widget _buildTeamCreatorName(String creatorId) {
    final creator = PersonaSessionController.quickGetUserById(creatorId);
    return Text(creator?.displayAlias ?? 'Unknown')
        .fontSize(14.sp)
        .fontWeight(FontWeight.bold)
        .textColor(KudoColors.black)
        .fontFamily(GoogleFonts.lato().fontFamily);
  }

  /// 构建团队操作按钮
  Widget _buildTeamActionButton(KiteTeamEntity team) {
    return Text('Get In Touch')
        .fontSize(14.sp)
        .fontWeight(FontWeight.w400)
        .textColor(KudoColors.yellow)
        .italic()
        .fontFamily(GoogleFonts.lato().fontFamily)
        .paddingHorizontal(8.w)
        .paddingVertical(2.h)
        .parent(
          ({required Widget child}) => Container(
            decoration: BoxDecoration(
              color: KudoColors.black,
              borderRadius: BorderRadius.circular(12.r),
            ),
            child: child,
          ),
        );
  }

  /// 处理团队点击事件
  void _handleTeamTap(KiteTeamEntity team) {
    // 导航到团队群聊页面
    AppNavigationManager.navigateToKiteTeamChat(context, team);
  }

  /// 构建联系人区域
  Widget _buildContactSection() {
    return Expanded(
      child: Column(
        crossAxisAlignment: CrossAxisAlignment.start,
        children: [
          // Contact标题
          Padding(
            padding: EdgeInsets.symmetric(horizontal: 16.w),
            child: Text('Contact')
                .fontSize(20.sp)
                .fontWeight(FontWeight.bold)
                .textColor(KudoColors.black)
                .fontFamily(GoogleFonts.lato().fontFamily),
          ),
          SizedBox(height: 16.h),
          // 联系人消息列表
          Expanded(child: _buildContactMessagesList()),
        ],
      ),
    );
  }

  /// 构建联系人消息列表
  Widget _buildContactMessagesList() {
    final sessions = KiteChatController.globalInstance.userChatSessionsState
        .reactiveValue(context);

    return sessions.isEmpty
        ? _buildEmptyContactList()
        : ListView.builder(
          padding: EdgeInsets.only(
            left: 16.w,
            right: 16.w,
            bottom: 100.h, // 添加底部空间，避免被底部导航栏挡住
          ),
          itemCount: sessions.length,
          itemBuilder: (context, index) {
            return _buildContactMessageItem(sessions[index]);
          },
        );
  }

  /// 构建空联系人列表提示
  Widget _buildEmptyContactList() {
    return Center(
      child: Image.asset(
        'assets/images/empty.png',
        width: 100.w,
        height: 100.h,
      ),
    );
  }

  /// 构建联系人消息项
  Widget _buildContactMessageItem(KiteChatSessionEntity session) {
    final currentUser =
        PersonaSessionController.globalInstance.currentPersonaState.value;
    if (currentUser == null) return const SizedBox.shrink();

    final otherUserId = session.getOtherParticipantId(
      currentUser.uniqueIdentifier,
    );
    final otherUser = PersonaSessionController.quickGetUserById(otherUserId);

    return Container(
      margin: EdgeInsets.only(bottom: 12.h),
      padding: EdgeInsets.all(16.w),
      decoration: BoxDecoration(
        color: KudoColors.green,
        borderRadius: BorderRadius.circular(16.r),
        boxShadow: [
          BoxShadow(
            color: KudoColors.black,
            offset: const Offset(0, 4),
            blurRadius: 0,
          ),
        ],
      ),
      child: Row(
        children: [
          // 用户头像
          ImageResourceHelper.buildCircularAvatar(
            imagePath: otherUser?.avatarResourceUrl ?? '',
            radius: 24.r,
            errorWidget: Icon(Icons.person, size: 24.r),
          ),
          SizedBox(width: 12.w),
          // 消息内容
          Expanded(
            child: Column(
              crossAxisAlignment: CrossAxisAlignment.start,
              children: [
                // 第一行：用户名和时间
                Row(
                  children: [
                    Text(otherUser?.displayAlias ?? 'Unknown')
                        .fontSize(16.sp)
                        .fontWeight(FontWeight.bold)
                        .textColor(KudoColors.black)
                        .fontFamily(GoogleFonts.lato().fontFamily)
                        .expanded(),
                    Text(
                          TimeDisplayHelper.formatTimeDisplay(
                            session.lastMessageTimestamp,
                          ),
                        )
                        .fontSize(12.sp)
                        .textColor(KudoColors.black.withValues(alpha: 0.6))
                        .fontFamily(GoogleFonts.lato().fontFamily),
                  ],
                ),
                SizedBox(height: 4.h),
                // 第二行：最新消息内容
                Text(
                  session.lastMessageContent,
                  style: TextStyle(
                    fontSize: 14.sp,
                    color: KudoColors.black.withValues(alpha: 0.8),
                    fontFamily: GoogleFonts.lato().fontFamily,
                  ),
                  maxLines: 1,
                  overflow: TextOverflow.ellipsis,
                ),
              ],
            ),
          ),
        ],
      ),
    ).inkWell(onTap: () => _handleContactTap(session));
  }

  /// 处理联系人点击事件
  void _handleContactTap(KiteChatSessionEntity session) {
    // 导航到私人聊天页面
    AppNavigationManager.navigateToKitePrivateChat(context, session);
  }
}
